package com.telit.firecommand.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.telit.common.util.JwtTokenUtils;
import com.telit.firecommand.dao.FireGrowExtendDao;
import com.telit.firecommand.dao.FirePopDao;
import com.telit.firecommand.dao.GeoXzqhCunDao;
import com.telit.firecommand.dto.FireGrowExtendDTO;
import com.telit.firecommand.entity.FireGrowExtend;
import com.telit.firecommand.entity.FirePop;
import com.telit.firecommand.enums.TransgerReportStatus;
import com.telit.firecommand.facade.FireGrowExtendTriggerFacadeService;
import com.telit.firecommand.service.GrowResponseService;
import com.telit.firecommand.vo.FireAlarmsPushVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * Create by Chencf 2022/08/29
 */
@Service
@Slf4j
public class GrowResponseServiceImpl implements GrowResponseService {

    @Autowired
    private FireGrowExtendDao fireGrowExtendDao;

    @Autowired
    private FirePopDao firePopDao;

    @Autowired
    private FireGrowExtendTriggerFacadeService fireGrowExtendTriggerFacadeService;

    @Autowired
    private GeoXzqhCunDao geoXzqhCunDao;

    @Override
    @Transactional
    public  Map growExtend(FireGrowExtendDTO dto) {
        //获取当前登录人属的账号地区
        String fireDistrictCode =dto.getUserDistrictCode();
        String realName = JwtTokenUtils.getRealName();
        Long userId = JwtTokenUtils.getId();
//        if (StringUtils.isEmpty(userDistrictCode)) {
//            userDistrictCode = dto.getUserDistrictCode();
//        }
        FireGrowExtend entity = new FireGrowExtend();
        entity.setTransferUserId(userId);
        entity.setTransferStatus(dto.getTransferStatus());
        String districtCode = null;
        String log = null;
        if (dto.getTransferStatus() == 1) {
            if (fireDistrictCode.length() > 6) {
                //乡镇级别账号
                //step 1 拿到火情所在的现行政区划位置，扩大到
                districtCode = dto.getUserDistrictCode().substring(0, 6);
                //根据行政区划查询对应乡
            } else if (fireDistrictCode.length() == 6) {
                //区县级账号，转到对应市级账号处理
                districtCode = dto.getUserDistrictCode().substring(0, 4);
            }else if (fireDistrictCode.length()==4){
                districtCode = dto.getUserDistrictCode().substring(0, 2);
            }
            String s = geoXzqhCunDao.queryNameByCode(dto.getFireDistrictCode(), dto.getFireDistrictCode().length());
            //谁将火情上报给谁
            //补全log  成都市xx县区xx乡镇发生火灾，请求扩大响应
            log = s + "发生火灾，请求扩大响应!" ;
        }
        //添加数据
        growExtendDTOParam(dto, entity, districtCode, log);
        fireGrowExtendDao.insert(entity);
        //添加到弹窗消息表中
        FirePop firePop = firePopParams(dto, districtCode);
        firePopDao.insert(firePop);
       //添加扩大响应标识
       // entity.setFlag(MsgIdentificationConstants.GROW_RESPONSE);
        //发送消息到对应层级的人员
        fireGrowExtendTriggerFacadeService.pushMsg(entity);
        Map<String, String> result = new HashMap<>();
        //根据行政区划查询对应名称
//        String districtCodeName = geoXzqhCunDao.queryOneNameByCode(districtCode, districtCode.length());
//        result.put("code",districtCode);
//        result.put("codeName",districtCodeName);

        return result;

    }


    //查询未读的火情
    @Override
    public List<FireAlarmsPushVO> getPop(String districtCode) {
        List<FireAlarmsPushVO> objects = new ArrayList<>();
        //批量查询火情信息
        List<FireAlarmsPushVO> fireAlarmsList = firePopDao.selectfireByFireids(districtCode);
        if (!CollectionUtils.isEmpty(fireAlarmsList)) {
            fireAlarmsList.forEach(fireAlarmsPushVO -> {
                //填充内容前端展示
                fireAlarmsPushVO.setTransferStatusStr(
                        TransgerReportStatus.code2Str(fireAlarmsPushVO.getTransferStatus()));
                if (org.apache.commons.lang3.StringUtils.isNotBlank(fireAlarmsPushVO.getAreaCode())) {
                    fireAlarmsPushVO.setAreaCodeName(geoXzqhCunDao.queryNameByCode(fireAlarmsPushVO.getAreaCode(),
                            fireAlarmsPushVO.getAreaCode().length()));
                }
                String content =
                        fireAlarmsPushVO.getTransferUser() + "给您" + fireAlarmsPushVO.getTransferStatusStr() + "一条火情";
                fireAlarmsPushVO.setContent(content);
                fireAlarmsPushVO.setSourceTypeStr(firePopDao.findDictNameByCode(fireAlarmsPushVO.getSourceType()));
            });
        }

        //将list进行分组
        Map<String, List<FireAlarmsPushVO>> collect = fireAlarmsList.stream().collect(
                Collectors.groupingBy(t -> t.getFireId()));
        //拿到分组里面时间最大的
        Set<Map.Entry<String, List<FireAlarmsPushVO>>> entries = collect.entrySet();
        for (Map.Entry<String, List<FireAlarmsPushVO>> entry : entries) {
            List<FireAlarmsPushVO> rule_result_type =
                    entry.getValue().stream().sorted(
                            Comparator.comparing(fireAlarmsPushVO -> String.valueOf(fireAlarmsPushVO.getTransferTime()),
                                    Comparator.reverseOrder())).collect(Collectors.toList());
            //排序完成取第一个
            objects.add(rule_result_type.get(0));//分组排序完 放入新的list

        }
//        List<FireAlarmsPushVO> result = objects.stream().filter(
//                fireAlarmsPushVO -> fireAlarmsPushVO.getTransferStatus().equals(transferStatus)).collect(
//                Collectors.toList());

        return objects;
    }

    //关闭弹窗
    @Override
    public void downPop(String fireId) {
        firePopDao.downPop(fireId);
    }

    //查询该火情资源范围
    @Override
    public Map isExtendFireScope(String fireId, String fireDistrictCode) {
        String resourceScopeDistrictCode=fireDistrictCode;
        //查询是否有过扩大响应
        QueryWrapper<FireGrowExtend> wrapper = new QueryWrapper<>();
        wrapper.eq("fire_id", fireId);
        wrapper.orderByDesc("create_time");
        wrapper.last("limit 1");
        FireGrowExtend fireGrowExtend = fireGrowExtendDao.selectOne(wrapper);
        if (Objects.isNull(fireGrowExtend)){
            resourceScopeDistrictCode=fireDistrictCode;
        }else {
            resourceScopeDistrictCode=fireGrowExtend.getDistrictCode();
        }

        Map<String, String> result = new HashMap<>();
        //根据行政区划查询对应名称
//        String districtCodeName = geoXzqhCunDao.queryOneNameByCode(resourceScopeDistrictCode, resourceScopeDistrictCode.length());
//        result.put("code",resourceScopeDistrictCode);
//        result.put("codeName",districtCodeName);


        return result;
    }

    //判断是否可以点击扩大响应按钮
    @Override
    @Transactional
    public Boolean isOkExtend(String districtCode, String fireId) {
        Boolean flag = true;
        FireGrowExtend fireGrowExtend = fireGrowExtendDao.selectByFireId(fireId);
        //拿到可以处理的行政区划code
        if (Objects.nonNull(fireGrowExtend)&&!districtCode.equals(fireGrowExtend.getDistrictCode())){
            flag=false;
        }
        return flag;
    }

    @Override
    public Boolean isFireHandle(String fireId,String userDistrictCode) {
        //加此接口的理由：因为存在火情的上报和转交的流程，这就导致省平台转交的火情只能对应到火情的市单位进行处理
        //同时，上报的逻辑也是如此  县上报的只能市处理，市上报的只能省处理  所以加此判断
        //step 1 查询该火情是否存在流转\
        Boolean isFire = true;
        Long userId = JwtTokenUtils.getId();
//        String userDistrictCode = JwtTokenUtils.getDistrictCode();
        QueryWrapper<FireGrowExtend> wrapper = new QueryWrapper<>();
        wrapper.eq("fire_id", fireId);
        wrapper.orderByDesc("create_time");
        List<FireGrowExtend> fireGrowExtends = fireGrowExtendDao.selectList(wrapper);
        List<Long> transferUserIdList = fireGrowExtends.stream().map(FireGrowExtend::getTransferUserId).collect(
                Collectors.toList());
        //可处理的行政区划code
        List<String> code = fireGrowExtends.stream().map(FireGrowExtend::getDistrictCode).collect(
                Collectors.toList());
        if (!CollectionUtils.isEmpty(transferUserIdList) && transferUserIdList.size() != 0) {
            //这部分可能需要调整  因为判断是否登录系统的账号可以处理该火情  判断长度可能不准确   判断长度相等还要判断code相等
            if (!transferUserIdList.get(0).equals(userId)) {
                isFire = true;
            } else {
                isFire = false;
            }
        }else {
            if (CollectionUtils.isEmpty(transferUserIdList)){
                if (userDistrictCode.length()<=6){
                    isFire=false;
                }
            }
        }
        return isFire;
    }


    private void growExtendDTOParam(FireGrowExtendDTO dto, FireGrowExtend entity, String districtCode,
                                     String log) {
        entity.setFireId(dto.getFireId());
        entity.setDistrictCode(districtCode);
        entity.setTransferStatus(dto.getTransferStatus());
        entity.setFireStatus(dto.getStatus());
        entity.setCreateTime(new Date());
        entity.setCreateUser(JwtTokenUtils.getRealName());
        entity.setLog(log);
        entity.setFireAdressCode(dto.getFireDistrictCode());
        entity.setLatitude(dto.getLatitude());
        entity.setLongitude(dto.getLongitude());
    }

    private FirePop firePopParams(FireGrowExtendDTO dto, String districtCode) {
        FirePop firePop = new FirePop();
        firePop.setFireId(dto.getFireId());
        firePop.setIsPop(0);
        firePop.setDistrictCode(districtCode);
        firePop.setCreateTime(new Date());
        return firePop;
    }

}
